package com.YHVision.qiuzhike.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.YHVision.qiuzhike.mapper.CompanyThumbMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.constant.CommonConstant;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.mapper.CompanyQuestionMapper;
import com.YHVision.qiuzhike.model.dto.companyQuestion.CompanyQuestionQueryRequest;
import com.YHVision.qiuzhike.model.entity.CompanyQuestion;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.CompanyQuestionVO;
import com.YHVision.qiuzhike.model.vo.UserVO;
import com.YHVision.qiuzhike.service.CompanyQuestionService;
import com.YHVision.qiuzhike.service.UserService;
import com.YHVision.qiuzhike.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企业问题关联服务实现
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@Service
@Slf4j
public class CompanyQuestionServiceImpl extends ServiceImpl<CompanyQuestionMapper, CompanyQuestion> implements CompanyQuestionService {

    @Resource
    private UserService userService;
    @Autowired
    private CompanyThumbMapper companyThumbMapper;

    /**
     * 校验数据
     *
     * @param companyQuestion
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validCompanyQuestion(CompanyQuestion companyQuestion, boolean add) {
        ThrowUtils.throwIf(companyQuestion == null, ErrorCode.PARAMS_ERROR);
        //不需要校验
//        // todo 从对象中取值
//        String title = companyQuestion.getTitle();
//        // 创建数据时，参数不能为空
//        if (add) {
//            // todo 补充校验规则
//            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
//        }
//        // 修改数据时，有参数则校验
//        // todo 补充校验规则
//        if (StringUtils.isNotBlank(title)) {
//            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
//        }
    }

    /**
     * 获取查询条件
     *
     * @param companyQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<CompanyQuestion> getQueryWrapper(CompanyQuestionQueryRequest companyQuestionQueryRequest) {
        QueryWrapper<CompanyQuestion> queryWrapper = new QueryWrapper<>();
        if (companyQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = companyQuestionQueryRequest.getId();
        Long notId = companyQuestionQueryRequest.getNotId();
        String sortField = companyQuestionQueryRequest.getSortField();
        String sortOrder = companyQuestionQueryRequest.getSortOrder();
        Long companyId = companyQuestionQueryRequest.getCompanyId();
        Long userId = companyQuestionQueryRequest.getUserId();
        Long questionId = companyQuestionQueryRequest.getQuestionId();
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(companyId), "companyId", companyId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取企业问题关联封装
     *
     * @param companyQuestion
     * @param request
     * @return
     */
    @Override
    public CompanyQuestionVO getCompanyQuestionVO(CompanyQuestion companyQuestion, HttpServletRequest request) {
        // 对象转封装类
        CompanyQuestionVO companyQuestionVO = CompanyQuestionVO.objToVo(companyQuestion);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = companyQuestion.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        companyQuestionVO.setUser(userVO);
        // endregion
        return companyQuestionVO;
    }

    /**
     * 分页获取企业问题关联封装
     *
     * @param companyQuestionPage
     * @param request
     * @return
     */
    @Override
    public Page<CompanyQuestionVO> getCompanyQuestionVOPage(Page<CompanyQuestion> companyQuestionPage, HttpServletRequest request) {
        List<CompanyQuestion> companyQuestionList = companyQuestionPage.getRecords();
        Page<CompanyQuestionVO> companyQuestionVOPage = new Page<>(companyQuestionPage.getCurrent(), companyQuestionPage.getSize(), companyQuestionPage.getTotal());
        if (CollUtil.isEmpty(companyQuestionList)) {
            return companyQuestionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<CompanyQuestionVO> companyQuestionVOList = companyQuestionList.stream().map(companyQuestion -> {
            return CompanyQuestionVO.objToVo(companyQuestion);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = companyQuestionList.stream().map(CompanyQuestion::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        companyQuestionVOList.forEach(companyQuestionVO -> {
            Long userId = companyQuestionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            companyQuestionVO.setUser(userService.getUserVO(user));
        });
        // endregion

        companyQuestionVOPage.setRecords(companyQuestionVOList);
        return companyQuestionVOPage;
    }

}
